package com.sx.pipeline.ui.area

import android.annotation.SuppressLint
import android.app.Application
import android.text.TextUtils
import android.widget.EditText
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.ToastUtils
import com.dinnovate.dxf.DXF
import com.dinnovate.dxf.collector.DxfCollector
import com.dinnovate.dxf.entity.GeometricPolyLine
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.sx.mvvmlibs.base.BaseViewModel
import com.sx.mvvmlibs.binding.edittext.viewAdapter
import com.sx.mvvmlibs.event.SingleLiveEvent
import com.sx.mvvmlibs.http.CommonObserver
import com.sx.mvvmlibs.utils.Logs
import com.sx.mvvmlibs.utils.RxThreadHelper
import com.sx.pipeline.app.model.CYBaseViewModel
import com.sx.pipeline.utils.GPSUtil
import com.sx.pipeline.utils.kml.FileParseBean
import com.sx.pipeline.utils.kml.FileParseBean.NodesBean
import com.sx.pipeline.utils.kml.KmlHelper
import java.io.File
import java.io.FileInputStream

/**
 * @Author: YY
 * @Date: 2022/8/4
 * @Desc: TODO
 */
class ImportFileVM(app: Application): CYBaseViewModel(app) {

    /**
     * Kml文件解析数据
     */
    val fileBeanListEvent: SingleLiveEvent<MutableList<FileParseBean>> = SingleLiveEvent()

    fun kmlAnalysis(kmlFile: File) {

        ThreadUtils.executeBySingle(object : ThreadUtils.Task<MutableList<FileParseBean>>() {

            override fun doInBackground(): MutableList<FileParseBean> {
                showLoadingDialog("正在解析...")
                return KmlHelper().parseKml(kmlFile)
            }

            override fun onSuccess(result: MutableList<FileParseBean>?) {
                dismissLoadingDialog()
                if (!result.isNullOrEmpty()) {
                    Logs.d("onSuccess LinePipeFilesVM ${result.size}")
                    if (result.size == 0) {
                        ToastUtils.showShort("KML文件不符合规范")
                        return
                    }
                    result.forEach {
                        if (it.type == 1) {
                            Logs.d("onSuccess LinePipeFilesVM${it.type}")
                            fileBeanListEvent.postValue(result)
                            return
                        }
                    }
                    fileBeanListEvent.postValue(result)
//                    fileTypeEvent.postValue(true)
                }
            }
            override fun onCancel() {
                dismissLoadingDialog()
            }

            override fun onFail(t: Throwable?) {
                dismissLoadingDialog()
                ToastUtils.showShort("文件解析失败")
            }
        })
    }


    /**
     * dxf文件解析数据
     */

    val dxfBeanListEvent: SingleLiveEvent<MutableList<FileParseBean>> = SingleLiveEvent()

    fun dxfAnalysis(dxfFile: File) {

        ThreadUtils.executeBySingle(object : ThreadUtils.Task<DxfCollector>() {
            override fun doInBackground(): DxfCollector {
                showLoadingDialog("正在解析...")
                return DXF.build(FileInputStream(dxfFile), "UTF-8")
            }

            override fun onSuccess(result: DxfCollector?) {
                dismissLoadingDialog()
                if (result != null) {
                    Logs.d("onSuccess ${result.map}")
                    Logs.d("onSuccess ${result.map.size}")
                    if (result.map.size > 1) {
                        ToastUtils.showShort("DXF文件不符合规范")
                        return
                    }
                    try {
                        val geometricPolyLine: List<GeometricPolyLine>? = result.map["LWPOLYLINE"] as List<GeometricPolyLine>
                        if (!geometricPolyLine.isNullOrEmpty()) {
                            var degrees1 = 114
                            var isPlus = false
                            if (geometricPolyLine[0].vertexList[0].x.toInt().toString().length > 6 ) {
                                isPlus = true
                                // 判断x轴 是否大于6位
                                val firstTwo = geometricPolyLine[0].vertexList[0].x.toInt().toString().substring(0, 2).toInt()
                                Logs.d("onSuccess $firstTwo")
                                degrees1 = if (firstTwo >= 24) {
                                    firstTwo * 3
                                } else {
                                    firstTwo * 6 - 3
                                }
                            }
                            showInputDialog(degrees1, geometricPolyLine, isPlus)
                        }
                    }catch (e:Exception){
                        ToastUtils.showShort("解析错误")
                    }
                }
            }

            override fun onCancel() {
                Logs.d("onCancel")
                dismissLoadingDialog()
            }

            override fun onFail(t: Throwable?) {
                Logs.d("onFail")
                dismissLoadingDialog()
            }
        })
    }

    /**
     * 添加负责区域
     */
    fun addTerritory(fileName: String) {
        Logs.d("addTerritory $fileName")
        if (TextUtils.isEmpty(fileName)) {
            ToastUtils.showShort("请输入文件名称")
            return
        }
        val fileParseBean: FileParseBean = if (fileName.endsWith(".kml")) {
            if (fileBeanListEvent.value.isNullOrEmpty()) {
                ToastUtils.showShort("请导入相关文件")
                return
            }
            fileBeanListEvent.value!![0]
        } else {
            if (dxfBeanListEvent.value.isNullOrEmpty()) {
                ToastUtils.showShort("请导入相关文件")
                return
            }
            dxfBeanListEvent.value!![0]
        }
       if (fileName.endsWith(".kml")) {
           fileParseBean.type = 1
       }else{
           fileParseBean.type = 2
       }
        fileParseBean.name = fileName
        addSubscribe(mModel.addTerritory(fileParseBean)
            .compose(RxThreadHelper.rxSchedulerHelper())
            .subscribeWith(object : CommonObserver<Any, BaseViewModel<*>>
                (this, true) {
                override fun onResult(result: Any) {
                    ToastUtils.showShort("添加成功")
                    finish()
                }

                override fun onFailed(code: Int, msg: String?) {
                    super.onFailed(code, msg)
                    ToastUtils.showShort(msg)
                }
            })
        )
    }

    @SuppressLint("StaticFieldLeak")
    private lateinit var mPopup: BasePopupView

    /**
     * 输入名称
     */
    private fun showInputDialog(degrees: Int,  geometricPolyLine: List<GeometricPolyLine>, isPlus: Boolean ) {
        mPopup = XPopup.Builder(ActivityUtils.getTopActivity())
            .autoDismiss(false)
            .asInputConfirm("中央子午线设置",
                "", degrees.toString(), "请输入中央子午线") {
                if (!TextUtils.isEmpty(it)) {
                    if (it.toInt() in 73..135) {
                        transformDxfData(it.toInt(), geometricPolyLine, isPlus)
                    } else {
                        ToastUtils.showShort("中央子午线超过国家范围")
                    }
                    mPopup.dismiss()
                } else {
                    ToastUtils.showShort("请输入中央子午线")
                }
            }.also {
                val editText = it.findViewById<EditText>(com.lxj.xpopup.R.id.et_input)
                viewAdapter.filterEditText(editText, true)
            }.show()
    }

    private fun transformDxfData(degrees: Int = 114, geometricPolyLine: List<GeometricPolyLine>, isPlus: Boolean) {
        val fileParseBeanList: MutableList<FileParseBean> = mutableListOf()
        val fileParse= FileParseBean()
        fileParse.type = 2

        val centerList: MutableList<NodesBean> = mutableListOf()
        geometricPolyLine.forEach { data ->
            data.vertexList.forEach { vertexList ->
                if (isPlus) {
                    // 如果带加号 去掉前两位
                    vertexList.x = vertexList.x.toString().substring(2).toBigDecimal()
                    Logs.d("transformDxfData ${vertexList.x.toDouble()}")
                }
                val nodesBean = NodesBean(
                    GPSUtil.CGS2000ToWGS84(vertexList.y.toDouble(), vertexList.x.toDouble(), degrees.toDouble())[1],
                    GPSUtil.CGS2000ToWGS84(vertexList.y.toDouble(), vertexList.x.toDouble(), degrees.toDouble())[0])
                centerList.add(nodesBean)
            }
            fileParse.nodesBeans = centerList
            fileParseBeanList.add(fileParse)
            dxfBeanListEvent.postValue(fileParseBeanList)
        }
    }
}